//
//  XMNetworkTools.swift
//  XMWeimo
//
//  Created by ios001 on 16/7/22.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

// 请求方式的枚举值
enum XMNetworkToolsType: String {
    case GET = "GET"
    case POST = "POST"
}

class XMNetworkTools: AFHTTPSessionManager {
    // 全局访问点
    static let shardTools: XMNetworkTools = {
        let tools = XMNetworkTools()
        // 指定反序列化格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    // 网络请求支持个体和post请求公共方法
    func request(type: XMNetworkToolsType, urlString: String, parameters: AnyObject?, success: (response: AnyObject?)->(), failure: (error: NSError)->()) {
        // get 请求
        if type == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: { (_, res) -> Void in
                success(response: res)
                }, failure: { (_, err) -> Void in
                    failure(error: err)
            })
        }else {
            // post 请求
            POST(urlString, parameters: parameters, progress: nil, success: { (_, res) -> Void in
                success(response: res)
                }, failure: { (_, err) -> Void in
                    failure(error: err)
            })
        }
        
    }
}

// MARK: - 请求OAuth界面数据
extension XMNetworkTools{
    // 请求userAccount
    func oauthLoadUserAccount(code: String, success: (response: AnyObject?)->(), failure: (error: NSError)->()){
        // 请求urlString
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 请求参数
        let params = [
            "client_id": APPKEY,
            "client_secret": APPSECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": APPREDIRECT_URL,
        ]
        request(XMNetworkToolsType.POST, urlString: urlString, parameters: params, success: success, failure: failure)
    }
    
    func oauthLoadUserInfo(userAccount: XMUserAccount, success: (response: AnyObject?)->(), failure: (error: NSError)->()){
        // 请求urlString
        let urlString = "https://api.weibo.com/2/users/show.json"
        // 请求参数
        let params = [
            "access_token": userAccount.access_token!,
            "uid": userAccount.uid!
        ]
        request(XMNetworkToolsType.GET, urlString: urlString, parameters: params, success: success, failure: failure)
    }
}

// MARK: - 请求首页微博界面数据
extension XMNetworkTools{
    // 请求首页数据
    func homeLoadData(sinceId: Int64, maxId: Int64, success: (response: AnyObject?)->(), failure: (error: NSError)->()){
        // 请求urlString
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        // 请求参数
        let params = [ "access_token": XMUserAccountViewModel.sharedTools.accessToken!,
                       "since_id":"\(sinceId)",
                       "max_id":"\(maxId)"
                     ]
        
        request(XMNetworkToolsType.GET, urlString: urlString, parameters: params, success: success, failure: failure)
    }
}

// MARK: - 发送微博
extension XMNetworkTools {
    // 发送文字微博
    func composeUpData(status: String, success: (response: AnyObject?)->(),failure: (error: NSError)->()){
        // 请求的url
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        // 请求参数
        let params = [
            "access_token":XMUserAccountViewModel.sharedTools.accessToken!,
            "status":status
        ]
        // 发送请求
        request(XMNetworkToolsType.POST, urlString: urlString, parameters: params, success: success, failure: failure)

    }
    
    // 发送图片微博
    func compserUpload(status: String, imageList: [UIImage], success: (response: AnyObject?)->(),failure: (error: NSError)->()){
        // 请求的url
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        // 请求参数
        let params = [
            "access_token":XMUserAccountViewModel.sharedTools.accessToken!,
            "status":status
        ]
        POST(urlString, parameters: params, constructingBodyWithBlock: { (formdata) -> Void in
            /*
            01: 客户端需要提交的二进制文件
            02: 服务器给客户端提供的名字 服务器才知道传的是什么模块里面的图片
            03: 服务器端保存文件的文件夹 客户端可以随意传
            04: 代表客户端提交的二进制文件格式,一般可以使用该类型 applicon/octet-stream 忽略格式
            */
            // 获取二进制数据
            // 发送一张图片
            //            let data = UIImagePNGRepresentation(self.composePictureView.imageList.first!)!
            //            formdata.appendPartWithFileData(data, name: "pic", fileName: "xiaomi", mimeType: "application/octet-stream")
            // 发送多张图片
            for i in 0..<imageList.count {
                let data = UIImagePNGRepresentation(imageList[i])!
                formdata.appendPartWithFileData(data, name: "pic", fileName: "xiaomi", mimeType: "application/octet-stream")
            }
            }, progress: nil, success: { (_, response) -> Void in
                success(response: response)
            }) { (_, error) -> Void in
                failure(error: error)
        }
    }
}